package study.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.reflect.FieldUtils;
import study.service.IResultHandler;

import java.util.function.Supplier;

/**
 * @author sunxuejian
 * @version 1.0
 * @date 2020/3/12 19:05
 */
@Slf4j
public final class RestUtil {

    private RestUtil() {}

    public static String genUrl(String gatewayName, String serviceName, String path) {
        return "http://" + gatewayName + "/" + serviceName + path;
    }

    private static DefaultHandleResult defaultHandleResult = new DefaultHandleResult();

    public static<T> T execute(Supplier<T> supplier) {
        return execute(supplier, defaultHandleResult);
    }

    public static <T> T execute(Supplier<T> supplier, IResultHandler resultHandler) {
        T result = sendReq(supplier);
        return resultHandler.checkResult(result);
    }


    public static <T> T sendReq(Supplier<T> supplier) {
        T result = null;

        try {
            result = supplier.get();
        } catch (Exception e) {
            throw new RestException("service call failed" + e.getMessage());
        } finally {
            log.info("result: " + result);
        }
        return result;
    }

    public static class DefaultHandleResult implements IResultHandler {

        @Override
        public <T> T checkResult(T result) {
            int code = 0;
            String message = "";

            try {
                code = (Integer) FieldUtils.readDeclaredField(result, "code", true);
                message = (String) FieldUtils.readDeclaredField(result, "message", true);
            } catch (IllegalAccessException e) {
                log.error(e.getMessage());
            }

            if(200 != code) {
                throw new RestException("code is error: code is" + code + ", message is" + message);
            }
            return result;
        }
    }
}
